import 'dart:io';

import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:flutter_download_plugin/flutter_download_plugin.dart';
import 'package:flutter_download_plugin/utils/download_utils.dart';
import 'package:flutter_download_plugin/utils/video/m3u8_downloader.dart';
import 'package:flutter_download_plugin/utils/video/m3u8_utils.dart';
import 'package:flutter_download_plugin/utils/video/video_utils.dart';
import 'package:flutter_hls_parser/flutter_hls_parser.dart';

void main() {
  runApp(const MaterialApp(
    home: MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  final _flutterDownloadPlugin = FlutterDownloadPlugin();

  //音视频分离m3u8_300kb,fmp4的分片方式
  String m3u8Url1 = "https://video.twimg.com/ext_tw_video/1875835592854081536/pu/pl/rfDwbsHm-zeWZiQf.m3u8?variant_version=1&tag=12&v=d7d";

  //电影m3u8_2GB
  String m3u8Url2 =
      "https://fenvixlight88.pro/file1/hQJBMwXbxhBrISMl7VNhrqWYTpMXktmBIEJP5kyoayd00Nl7G5sqWAJKwoCkBcsTnq~M0d6p07aLa2UjRc3lZt9NwOmltFoEr6~YjnJk3xirp3OIvKEX0cHTRiTmzHQjkmbRHWWz5xtrR8DfA7WkTi9AG92oalNnFHCLq9ItvsQ=/cGxheWxpc3QubTN1OA==.m3u8";

  //音视频分离m3u8_463M
  String m3u8Url3 = "https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8";

  //简单TS文件m3u8_65M
  String m3u8Url4 = "https://sf1-cdn-tos.huoshanstatic.com/obj/media-fe/xgplayer_doc_video/hls/xgplayer-demo.m3u8";

  //苹果时钟测试457M
  String m3u8Url5 = "https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8";

  //这是一个加密流2G
  String m3u8Url6 = "https://bi tdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8";

  //带字幕流400M
  String m3u8Url7 = "https://d2zihajmogu5jn.cloudfront.net/bipbop-advanced/bipbop_16x9_variant.m3u8";

  //DAHS和HLS混合流
  String m3u8Url8 = "https://dash.akamaized.net/dash264/TestCases/1c/qualcomm/1/MultiRate.mpd";

  //多码率自适应流125M
  String m3u8Url9 = "https://bitdash-a.akamaihd.net/content/MI201109210084_1/m3u8s/f08e80da-bf1d-4e3d-8899-f0f6155f6efa.m3u8";

  //46秒
  String videoUrl1 = "http://vjs.zencdn.net/v/oceans.mp4";

  //17秒广告
  String videoUrl2 = "https://ht-cdn2.adtng.com/a7/creatives/221/1559/820683/1125055/1125055_video.mp4";

  //9分54秒，国外mp4
  String videoUrl3 = "http://mirror.aarnet.edu.au/pub/TED-talks/911Mothers_2010W-480p.mp4";

  //flv  30.05M
  String videoUrl4 = "https://www.sample-videos.com/video321/flv/480/big_buck_bunny_480p_30mb.flv";

  //mkv 2M
  String videoUrl5 = "https://www.sample-videos.com/video321/mkv/720/big_buck_bunny_720p_2mb.mkv";

  //3gp 10M
  String videoUrl16 = "https://www.sample-videos.com/video321/3gp/144/big_buck_bunny_144p_10mb.3gp";

  //ts 2.3M
  String videoUrl7 = "https://test-streams.mux.dev/x36xhzz/url_0/url_464/193039199_mp4_h264_aac_hd_7.ts";

  var testText = "测试文本";
  Timer? timer;
  List<CustomDownloadTask> taskList = [];

  @override
  void initState() {
    super.initState();
    initPlatformState();
    DownloadUtils.initDownloadConfig();

    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      refreshList();
    });
  }

  @override
  void dispose() {
    if (timer != null) {
      timer!.cancel();
    }
    super.dispose();
  }

  void refreshList() async {
    // taskList.clear();
    // taskList.addAll(M3u8Downloader().getTaskQueue());
    // print(taskList);
    // taskList.addAll(await DownloadUtils.allRecords());
    taskList = await DownloadUtils.allRecords();

    setState(() {});
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      platformVersion = await _flutterDownloadPlugin.getPlatformVersion() ?? 'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  // /// 选择不同的媒体流
  Future<int> onSelectVariant(List<Variant> variants) async {
    return await showDialog<int>(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text('选择一个下载流'),
              content: SingleChildScrollView(
                child: ListBody(
                  children: List.generate(variants.length, (i) {
                    return ListTile(
                      title: Text("${variants[i].format.width}*${variants[i].format.height}"),
                      onTap: () {
                        Navigator.pop(context, variants.indexOf(variants[i])); // 返回选择的索引
                      },
                    );
                  }),
                ),
              ),
            );
          },
        ) ??
        0; // 如果用户取消选择，返回 -1
  }

  /// 选择码率对话框
  void selectDialog(
    BuildContext context,
    List<Variant> variants, {
    required void Function(int index) onSelect,
  }) {
    if (variants.isEmpty || variants.length == 1) {
      onSelect(0);
      return;
    }
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('选择一个下载流'),
          content: SingleChildScrollView(
            child: ListBody(
              children: List.generate(variants.length, (i) {
                return ListTile(
                  title: Text("${variants[i].format.width}*${variants[i].format.height}"),
                  onTap: () {
                    Navigator.pop(context);

                    onSelect(i);
                  },
                );
              }),
            ),
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("下载页面测试"),
      ),
      body: Column(children: [
        SizedBox(
          width: double.infinity,
          height: 300,
          child: SingleChildScrollView(
            child: Wrap(
              children: [
                ElevatedButton(
                  onPressed: () async {
                    List<Variant> variants = await M3u8Utils.getM3u8variantListByUrl(url: m3u8Url1);

                    selectDialog(context, variants, onSelect: (int i) {
                      DownloadUtils.download(
                        urlList: [m3u8Url1],
                        variantIndex: i,
                        displayName: "音视频分离m3u8_300kb",
                      );

                      refreshList();
                    });
                  },
                  child: Text("音视频分离m3u8_300kb"),
                ),
                ElevatedButton(
                  onPressed: () async {
                    List<Variant> variants = await M3u8Utils.getM3u8variantListByUrl(url: m3u8Url2);

                    selectDialog(context, variants, onSelect: (int i) {
                      DownloadUtils.download(
                        urlList: [m3u8Url2],
                        variantIndex: i,
                        displayName: "电影m3u8_2GB",
                      );

                      refreshList();
                    });
                  },
                  child: Text("电影m3u8_2GB"),
                ),
                ElevatedButton(
                  onPressed: () async {
                    List<Variant> variants = await M3u8Utils.getM3u8variantListByUrl(url: m3u8Url3);

                    selectDialog(context, variants, onSelect: (int i) {
                      DownloadUtils.download(
                        urlList: [m3u8Url3],
                        variantIndex: i,
                        displayName: "音视频分离m3u8_463M",
                      );

                      refreshList();
                    });
                  },
                  child: Text("音视频分离m3u8_463M"),
                ),
                ElevatedButton(
                  onPressed: () async {
                    List<Variant> variants = await M3u8Utils.getM3u8variantListByUrl(url: m3u8Url4);

                    selectDialog(context, variants, onSelect: (int i) {
                      DownloadUtils.download(
                        urlList: [m3u8Url4],
                        variantIndex: i,
                        displayName: "简单TS文件m3u8_65M",
                      );

                      refreshList();
                    });
                  },
                  child: Text("简单TS文件m3u8_65M"),
                ),
                ElevatedButton(
                  onPressed: () async {
                    List<Variant> variants = await M3u8Utils.getM3u8variantListByUrl(url: m3u8Url5);

                    selectDialog(context, variants, onSelect: (int i) {
                      DownloadUtils.download(
                        urlList: [m3u8Url5],
                        variantIndex: i,
                        displayName: "苹果时钟测试457M",
                      );

                      refreshList();
                    });
                  },
                  child: Text("苹果时钟测试457M"),
                ),
                ElevatedButton(
                  onPressed: () async {
                    List<Variant> variants = await M3u8Utils.getM3u8variantListByUrl(url: m3u8Url6);

                    selectDialog(context, variants, onSelect: (int i) {
                      DownloadUtils.download(
                        urlList: [m3u8Url6],
                        variantIndex: i,
                        displayName: "加密流2G",
                      );

                      refreshList();
                    });
                  },
                  child: Text("加密流2G"),
                ),
                ElevatedButton(
                  onPressed: () async {
                    List<Variant> variants = await M3u8Utils.getM3u8variantListByUrl(url: m3u8Url7);

                    selectDialog(context, variants, onSelect: (int i) {
                      DownloadUtils.download(
                        urlList: [m3u8Url7],
                        variantIndex: i,
                        displayName: "带字幕流400M",
                      );

                      refreshList();
                    });
                  },
                  child: Text("带字幕流400M"),
                ),
                ElevatedButton(
                  onPressed: () async {
                    List<Variant> variants = await M3u8Utils.getM3u8variantListByUrl(url: m3u8Url8);

                    selectDialog(context, variants, onSelect: (int i) {
                      DownloadUtils.download(
                        urlList: [m3u8Url8],
                        variantIndex: i,
                        displayName: "DAHS和HLS混合流",
                      );

                      refreshList();
                    });
                  },
                  child: Text("DAHS和HLS混合流"),
                ),
                ElevatedButton(
                  onPressed: () async {
                    List<Variant> variants = await M3u8Utils.getM3u8variantListByUrl(url: m3u8Url9);

                    selectDialog(context, variants, onSelect: (int i) {
                      DownloadUtils.download(
                        urlList: [m3u8Url9],
                        variantIndex: i,
                        displayName: "多码率自适应流125M",
                      );

                      refreshList();
                    });
                  },
                  child: Text("多码率自适应流125M"),
                ),
                ElevatedButton(
                  onPressed: () {
                    DownloadUtils.download(
                      urlList: [videoUrl1],
                    );

                    refreshList();
                  },
                  child: Text("MP4_46秒"),
                ),
                ElevatedButton(
                  onPressed: () {
                    DownloadUtils.download(
                      urlList: [videoUrl2],
                    );
                  },
                  child: Text("MP4_17秒广告"),
                ),
                ElevatedButton(
                  onPressed: () {
                    DownloadUtils.download(
                      urlList: [videoUrl3],
                    );
                  },
                  child: Text("MP4_9分54秒国外"),
                ),
                ElevatedButton(
                  onPressed: () {
                    DownloadUtils.download(
                      urlList: [videoUrl4],
                    );
                  },
                  child: Text("FLV_30M"),
                ),
                ElevatedButton(
                  onPressed: () {
                    DownloadUtils.download(
                      urlList: [videoUrl5],
                    );
                  },
                  child: Text("mkv_2m"),
                ),
                ElevatedButton(
                  onPressed: () {
                    DownloadUtils.download(
                      urlList: [videoUrl16],
                    );
                  },
                  child: Text("3gp_10m"),
                ),
                ElevatedButton(
                  onPressed: () {
                    DownloadUtils.download(
                      urlList: [videoUrl7],
                    );
                  },
                  child: Text("ts_2.3m"),
                ),
                ElevatedButton(
                  onPressed: () {
                    DownloadUtils.pauseAll();

                    // M3u8Downloader().pauseAllDownload();

                    refreshList();
                  },
                  child: Text("暂停所有下载"),
                ),
                ElevatedButton(
                  onPressed: () {
                    DownloadUtils.resumeAll();

                    // M3u8Downloader().resumeAllDownload();
                    refreshList();
                  },
                  child: Text("恢复所有下载"),
                ),
                ElevatedButton(
                  onPressed: () async {
                    await DownloadUtils.deleteAll();
                    taskList.clear();

                    refreshList();
                  },
                  child: Text("删除所有下载记录"),
                ),
                ElevatedButton(
                  onPressed: () {
                    refreshList();
                  },
                  child: Text("查询所有下载记录"),
                ),
              ],
            ),
          ),
        ),
        Expanded(
          child: Container(
            padding: const EdgeInsets.all(10),
            width: double.infinity,
            child: ListView.separated(
              itemCount: taskList.length,
              itemBuilder: (BuildContext context, int index) {
                return Container(
                  color: Colors.grey,
                  padding: const EdgeInsets.all(10),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      if (taskList[index].cover != null)
                        SizedBox(width: 100, height: 100, child: Image(image: FileImage(File(taskList[index].cover!)))),
                      Text(
                        taskList[index].displayName ?? taskList[index].fileName,
                        maxLines: 3,
                      ),
                      Text(
                        taskList[index].status.toString(),
                        maxLines: 2,
                      ),
                      Text(
                        taskList[index].filePath,
                        maxLines: 3,
                      ),
                      Row(
                        children: [
                          // if (taskList[index].status == TaskStatus.complete.toString())
                          //   ElevatedButton(
                          //     onPressed: () {
                          //       // Get.dialog(BrowserVideoPreview(BrowserResourceItem(url: taskList[index].filePath)), barrierColor: Colors.black87);
                          //     },
                          //     child: Text("播放"),
                          //   ),
                          ElevatedButton(
                            onPressed: () {
                              DownloadUtils.pause(taskList[index].taskId);

                              refreshList();
                            },
                            child: Text("暂停"),
                          ),
                          ElevatedButton(
                            onPressed: () {
                              DownloadUtils.deleteTasksByIds([taskList[index].taskId]);

                              refreshList();
                            },
                            child: Text("删除"),
                          ),
                        ],
                      ),
                      Row(
                        children: [
                          Text(
                            "下载进度${(taskList[index].progress * 100).toStringAsFixed(1)}%",
                            maxLines: 2,
                          ),
                          const SizedBox(
                            width: 16,
                          ),
                          Text(
                            "下载速度${VideoUtils.calculateSpeed(taskList[index].totalSpeed)}",
                            maxLines: 2,
                          ),
                        ],
                      ),
                    ], // 假设 taskList 中存储的是字符串
                  ),
                );
              },
              separatorBuilder: (BuildContext context, int index) {
                return Divider();
              },
            ),
          ),
        ),
      ]),
    );
  }
}
